package com.efounder.zone.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.pansoft.chat.photo.JFPicturePickPhotoWallActivity;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.ResStringUtil;
import com.efounder.zone.R;
import com.efounder.zone.adapter.CommentImageAdapter;
import com.efounder.zone.bean.TalksBean;
import com.efounder.zone.commentview.ZoneCommentBean;
import com.efounder.zone.event.MobileZoneEvent;
import com.efounder.zone.event.MobileZoneRefreshEvent;
import com.efounder.zone.util.CreateBeanUtil;
import com.efounder.zone.util.ZoneRequestUtil;
import com.efounder.zone.widget.StatusAlert;
import com.utilcode.util.ActivityUtils;
import com.utilcode.util.KeyboardUtils;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static com.efounder.chat.fragment.ChatSenderFragment.chatpath;
import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.pansoft.chat.photo.JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE;

/**
 * @author will
 * 评论输入组件
 */
public class CommentInputDialogFragment extends DialogFragment implements View.OnClickListener{

    private static final String TAG = "CommentInputDialogFragment";
    private EditText etComment;//评论输入框
    private LinearLayout llCommentImage;//评论图片展示view
    private RecyclerView recyclerView; //图片评论recyclerview
    private CommentImageAdapter commentImageAdapter;
    private Button btnSend;
    private TalksBean talksBean;
    private int position;
    private ZoneCommentBean zoneCommentBean;//回复的目标评论
    private boolean replyToComment = false;//是否是回复给评论的评论
    private ArrayList<String> images = new ArrayList<>();//图片评论list
    private ArrayList<String> imgUrlList = new ArrayList<>();//图片评论url
    private String comment = "";//评论内容

    public CommentInputDialogFragment() {
    }

    @Override
    public void onStart() {
        super.onStart();
        getDialog().getWindow()
                .setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        getDialog().getWindow().setGravity(Gravity.BOTTOM);
        getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);//支持输入法
        getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        getDialog().setCanceledOnTouchOutside(true);
        getDialog().setCancelable(true);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomDialog);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.mobile_zone_comment_input, container, false);
        initView(rootView);
        return rootView;
    }

    public void setParams(Context context, int position, TalksBean talksBean, ZoneCommentBean zoneCommentBean) {
        this.position = position;
        this.talksBean = talksBean;
        this.zoneCommentBean = zoneCommentBean;
    }

    private void initView(View view) {
        ImageView ivAt, ivEmoji, ivPhoto;
//        ivAt = view.findViewById(R.id.iv_at);
//        ivAt.setOnClickListener(this);
//        ivEmoji = view.findViewById(R.id.iv_emoji);
//        ivEmoji.setOnClickListener(this);
        ivPhoto = view.findViewById(R.id.iv_photo);
        ivPhoto.setOnClickListener(this);
        etComment = view.findViewById(R.id.et_comment);
        etComment.setHint(ResStringUtil.getString(R.string.zone_comment));
        if (zoneCommentBean != null) {
            User user = WeChatDBManager.getInstance().getOneUserById(zoneCommentBean.getCommentUserId());
            if (user.getNickName() != null && !user.getNickName().equals("")) {
                etComment.setHint(ResStringUtil.getString(R.string.zone_reply_to)+user.getNickName());
            } else if (zoneCommentBean.getCommentUserNickname()!=null && !zoneCommentBean.getCommentUserNickname().equals("")){
                etComment.setHint(ResStringUtil.getString(R.string.zone_reply_to)+zoneCommentBean.getCommentUserNickname());
            }
        }
        etComment.setFocusable(true);
        btnSend = view.findViewById(R.id.button_send);
        btnSend.setOnClickListener(this);
        btnSend.setEnabled(false);

        etComment.post(new Runnable() {
            @Override
            public void run() {
                etComment.setFocusableInTouchMode(true);
                etComment.requestFocus();
                KeyboardUtils.showSoftInput(etComment);
            }
        });
        etComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etComment.getText().toString().equals("")) {
                    btnSend.setEnabled(false);
                }else {
                    btnSend.setEnabled(true);
                }
            }
        });
        etComment.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_SEND &&
                        btnSend.isEnabled()) {
                    dealComment();
                    handled = true;
                }
                return handled;
            }
        });
        //图片评论view
        llCommentImage = view.findViewById(R.id.ll_comment_photo);
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(ActivityUtils.getTopActivity(), LinearLayoutManager.HORIZONTAL,
                false));
        commentImageAdapter = new CommentImageAdapter(ActivityUtils.getTopActivity(), images);
        recyclerView.setAdapter(commentImageAdapter);
        commentImageAdapter.setOnImgRemovedListener(new CommentImageAdapter.OnImgRemovedListener() {
            @Override
            public void onImgRemoved(int position) {
                images.remove(position);
                if (images.size() <= 0) {
                    if (etComment.getText().toString().equals("")) btnSend.setEnabled(false);
                    llCommentImage.setVisibility(View.GONE);
                }
                commentImageAdapter.notifyItemRemoved(position);
            }
        });
        //初始图片评论view不可见
        llCommentImage.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.button_send) {
            dealComment();
        } else if (id == R.id.iv_photo) {
            Intent intent = new Intent(ActivityUtils.getTopActivity(), JFPicturePickPhotoWallActivity.class);
            intent.putExtra("mPictureList", images);
            intent.putExtra(JFPicturePickPhotoWallActivity.MAX_NUM, 3);//可选择的最大照片数
            intent.putExtra("sendBtnName", ResStringUtil.getString(R.string.common_text_confirm));
            intent.putExtra(JFPicturePickPhotoWallActivity.SHOW_RAW_PIC, false);
            startActivityForResult(intent, REQUEST_PIC_SELECTE_CODE);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    /**
     * 处理评论
     */
    private void dealComment() {
        comment = etComment.getText().toString();
        if (images.size() > 0) {
            LoadingDataUtilBlack.show(ActivityUtils.getTopActivity(),ResStringUtil.getString(R.string.common_text_please_wait));
            //压缩图片并上传
            for (int i = 0; i < images.size(); i++) {
                //如果不是gif动图则进行裁剪压缩
                if (!ImageUtil.isGifFile((new File(images.get(i))))) {
                    ImageUtil.saveNewImage(images.get(i), 1280, 1280);
                    uploadImage(chatpath + ImageUtil.getFileName(images.get(i)) + ".pic");
                } else {
                    uploadImage(images.get(i));
                }
            }
        }else {
            //纯文字评论
            comment = new CreateBeanUtil().createComment(comment, new ArrayList<String>());
            sendComment();
        }
        dismiss();
    }
    /**
     * 发送评论
     * @param position 评论所在状态的position
     * @param commentBean 评论内容
     */
    private void sendComment(final int position, final TalksBean.CommentBean commentBean, final TalksBean.CommentBean.ChildCommentsBean childCommentsBean) {
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
        params.put("password", EnvironmentVariable.getProperty(CHAT_PASSWORD));

        //回复给评论,则增加这两个参数
        if (childCommentsBean != null) {
            replyToComment = true;
            //评论的用户id
            params.put("replyUserId", String.valueOf(childCommentsBean.getReplyUserId()));
            //评论的id
            params.put("commentParent", String.valueOf(childCommentsBean.getParentId()));
            //动态类型
            params.put("commentObjectType", String.valueOf(childCommentsBean.getObjectType()));
            //动态id
            params.put("commentObjectId", String.valueOf(childCommentsBean.getObjectId()));

            params.put("commentContent", childCommentsBean.getContent());
        } else {
            replyToComment = false;
            //动态类型
            params.put("commentObjectType", String.valueOf(commentBean.getObjectType()));
            //动态id
            params.put("commentObjectId", String.valueOf(commentBean.getObjectId()));

            params.put("commentContent", commentBean.getContent());
        }
        LoadingDataUtilBlack.show(ActivityUtils.getTopActivity(),ResStringUtil.getString(R.string.common_text_please_wait));
        ZoneRequestUtil.postCommonRequest(TAG, "comments", params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                Log.d("CommentSuccess", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.has("commentid")) {
                        StatusAlert.successAlert(ActivityUtils.getTopActivity(), LayoutInflater.from(ActivityUtils.getTopActivity())
                                .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_comment_success));
                        //如果position == 0, 约定为从消息界面回复的评论，不需要刷新界面
                        if (position == 0) {
                            return;
                        }
                        //todo 设置积分
                        int integral=0;
                        try {
                            integral = jsonObject.optInt("integral",talksBean.getObj().getIntegral());
                            talksBean.getObj().setIntegral(integral);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        //刷新界面
                        List<TalksBean.CommentBean> commentBeanList = talksBean.getComment();
                        if (replyToComment) {
                            //回复给评论，将评论加在父评论里面
                            int parentId = (int) childCommentsBean.getParentId();
                            for (int i = 0; i < commentBeanList.size(); i++) {
                                //循环找出父评论
                                if (commentBeanList.get(i).getId() == parentId) {
                                    if (commentBeanList.get(i).getChildComments() == null) {
                                        List<TalksBean.CommentBean.ChildCommentsBean> list = new ArrayList<>();
                                        commentBeanList.get(i).setChildComments(list);
                                    }
                                    childCommentsBean.setId(jsonObject.optInt("commentid"));
                                    commentBeanList.get(i).getChildComments().add(childCommentsBean);
                                }
                            }
                        } else {
                            commentBean.setId(jsonObject.optInt("commentid"));
                            commentBeanList.add(commentBean);
                        }
                        replyToComment = false;
                        EventBus.getDefault().post(new MobileZoneEvent(position));
                        EventBus.getDefault().post(new MobileZoneRefreshEvent(talksBean, null));
                    }else {
                        StatusAlert.failAlert(ActivityUtils.getTopActivity(), LayoutInflater.from(ActivityUtils.getTopActivity())
                                .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_comment_fail));
                    }
                } catch (Exception e) {
                    StatusAlert.failAlert(ActivityUtils.getTopActivity(), LayoutInflater.from(ActivityUtils.getTopActivity())
                            .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_comment_fail));
                }

            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                StatusAlert.failAlert(ActivityUtils.getTopActivity(), LayoutInflater.from(ActivityUtils.getTopActivity())
                        .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_comment_fail));
                Log.d("CommentFail", error);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PIC_SELECTE_CODE
                && resultCode == RESULT_OK) {
            //图库选择照片
            images.clear();
            images.addAll((ArrayList<String>) data.getExtras().get("mSelectedPics"));
            if (images.size() > 0) {
                //有图片则显示view，刷新
                btnSend.setEnabled(true);
                llCommentImage.setVisibility(View.VISIBLE);
                commentImageAdapter.notifyDataSetChanged();
            }else {
                //无图片，则隐藏view
                if (etComment.getText().toString().equals("")) btnSend.setEnabled(false);
                llCommentImage.setVisibility(View.GONE);
                commentImageAdapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 上传图片，完成后发送评论
     * @param imgAddress 待上传图片的本地路径
     */
    private void uploadImage(String imgAddress) {
        PansoftCloudUtil.getCloudRes(imgAddress, new PansoftCloudUtil.UpLoadListener() {
            @Override
            public void getHttpUrl(Boolean isSuccess, String url) {
                if (isSuccess) {
                    Log.i("MyUserInfoActivity", R.string.zone_path_of_photo + url);
                    imgUrlList.add(url);
                    //如果返回的url list 和原图片 list 大小一致，则上传成功
                    if (images.size() == imgUrlList.size()) {
                        comment = new CreateBeanUtil().createComment(comment, imgUrlList);
                        LoadingDataUtilBlack.dismiss();
                        sendComment();
                    }
                } else {
                    //图片没有上传成功
                    LoadingDataUtilBlack.dismiss();
                    ToastUtils.showShort(R.string.common_text_upload_fail_again);
                    imgUrlList.clear();
                }
            }
        });
    }

    /**
     * 发送评论
     */
    private void sendComment() {
        //如果position == 0, 约定为从消息界面回复的评论，不需要刷新界面
        if (position == 0) {
            //回复评论
            TalksBean.CommentBean.ChildCommentsBean commentBean = new CreateBeanUtil()
                    .createReplyCommentBean(talksBean.getObj().getId(),
                            talksBean.getObjType(), zoneCommentBean.getParentId() == null || (int)zoneCommentBean.getParentId() == 0 ? zoneCommentBean.getId() : (int) zoneCommentBean.getParentId(),
                            zoneCommentBean.getCommentUserId(), comment);
            sendComment(position, null, commentBean);
            return;
        }
        //正常界面的评论
        if (zoneCommentBean!=null) {
            //回复评论
            TalksBean.CommentBean.ChildCommentsBean commentBean = new CreateBeanUtil()
                    .createReplyCommentBean(talksBean.getObj().getId(),
                            talksBean.getObjType(), zoneCommentBean.getParentId() == null ? zoneCommentBean.getId() : (int) zoneCommentBean.getParentId(),
                            zoneCommentBean.getCommentUserId(), comment);
            sendComment(position, null, commentBean);
        }else {
            //回复动态
            TalksBean.CommentBean commentBean = new CreateBeanUtil()
                    .createNewTalksCommentBean(talksBean.getObj().getId(),
                            talksBean.getObjType(), comment);
            sendComment(position, commentBean, null);
        }
    }
}
